//
//  LDBossMeVC.swift
//  DingDongZP
//
//  Created by 三秒文化 on 16/6/8.
//  Copyright © 2016年 iyhjiang.com. All rights reserved.
//

import UIKit
import APParallaxHeader

@objc(LDBossMeVC) class LDBossMeVC: UIViewController {
    
    
    var cellmodels = meListCellModel()
    var model:LDBossBaseInfoModel?
    var tableView:UITableView!
    
    let kBossInfoCompelete = "isBossInfoCompelete"
    let kCompanyInfoCompelete = "isCompanyInfoCompelete"
    
    var isBossInfoCompelete:Bool = false
    var isCompanyInfoCompelete:Bool = false
    
    lazy var headerViewTransImg:UIImage = {
        
        let image = UIImage.setImageWithColor(LDGolbalColor.Green.colorWithAlphaComponent(0))
        return image
    }()
    var headViewH:CGFloat = IPHONE6UP ? 330 : 310
    
    lazy var headerViewGreenImg:UIImage = {
        
        let image = UIImage.setImageWithColor(LDGolbalColor.Green.colorWithAlphaComponent(1))
        return image
    }()
    
    lazy var footerBackSectionGound :UIView = {
        
        let view = UIView()
        view.backgroundColor = LDGolbalColor.BgGoundGray
        return view
        
    }()
    
    lazy var headerBackSectionGound :UIView = {
        
        let view = UIView()
        view.backgroundColor = LDGolbalColor.BgGoundGray
        return view
        
    }()
    
    var headview:LDBossMeHeaderView?
    
    //可根据xml配置
    var listArr:[DDAPPConfigureModel_DesktopMe_Item] = [DDAPPConfigureModel_DesktopMe_Item]()
    
    override func viewDidLoad() {
        
        super.viewDidLoad()
        
        setTabbleView()
        setupNav()
        setData()
    }
    
    override func viewWillAppear(animated: Bool) {
        
        setNavTransparent()
        request()
//        isAccess()
        setData()
    }
    
    func setData() {
        
        guard let appmodel = LDAPPConfigureManager.configureManger.appConfigureModel else { return }
        guard let apptype = appmodel.apptype else { return }
        
        _ = apptype.enumerate().contains { [weak self] (value) -> Bool in
            
            if value.element.id == "2-0-0" {
                
                debugPrint("version--- 2-0-0")
                self?.listArr = apptype[value.index].desktop.desktop_me.meitem ?? [DDAPPConfigureModel_DesktopMe_Item]()
                
                
                
                self?.listArr = self!.listArr.flatMap { (item) -> DDAPPConfigureModel_DesktopMe_Item? in
                    
                    if item.enable == "true" {
                        
                        return item
                    }; return nil
                }
                
//                debugPrint("version---",self!.isEmployer)
                
                return true
            }
            
            return false
        }
        
        tableView.reloadData()
    }
    
    
    
    
    
//    override func viewWillDisappear(animated: Bool) {
//    
//        navigationController?.navigationBar.translucent = false
//        self.navigationController?.navigationBar.setBackgroundImage(headerViewGreenImg, forBarMetrics: UIBarMetrics.Default)
//    }
    
    //透明
    func setNavTransparent() {
        
        navigationController?.navigationBar.setBackgroundImage(headerViewTransImg, forBarMetrics: UIBarMetrics.Default)
        navigationController?.navigationBar.shadowImage = headerViewTransImg
        rdv_tabBarController.setTabBarHidden(false, animated: false)
    }
    
    func setTabbleView() {
        
        tableView = LDBaseTableView.init(frame: CGRectMake(0, 0, view.width, view.height - 49), style: .Grouped)
        
        tableView.separatorStyle = .None
        tableView.delegate = self
        tableView.dataSource = self
        view.addSubview(tableView)
        
        headview = LDBossMeHeaderView(frame: CGRectMake(0, 0, LDFrame.ScreenWidth, headViewH))
        tableView.addParallaxWithView(headview, andHeight: CGRectGetHeight(headview!.frame))
        headviewContentsClick()
        
    }
    
    func request() {
        
        LDBossInfoNet.sharedInstance.queryProfileInfo({ [weak self] (dict) in
            
            self?.model = LDBossBaseInfoModel.yy_modelWithDictionary(dict as [NSObject : AnyObject])
            self?.headview?.model = self?.model
            
            self?.updateCellDesc()
            
        }, failure: nil)
        
        LDBossInfoNet.sharedInstance.queryAllPublishJob({ [weak self] (dictArr) in
            
            
            let infoarr = dictArr ?? NSArray()
            if infoarr.count > 0 {
                
                let jobtitle = "成功发布了 " + "\(infoarr.count)" + " 个职位"
                
                let customLabel = DDCustomLabel()
                customLabel.textColor = LDFontColor.BlackLight
                customLabel.text = jobtitle
                
                customLabel.setAttributeLabelWithtextColorPairs([["\(infoarr.count)":LDFontColor.Green]])
                self?.headview?.publishStatusLabel.attributedText = customLabel.attributedText
                self?.headview?.publishStatusLabel.font = UIFont.systemFontOfSize(14)
            }
            
        }) { (error) in
            
            
        }
    }
    
    func updateCellDesc() {
        
        //钱包2-4-1 //待面试2-4-2 //感兴趣的牛人2-4-5 沟通过的牛人2-4-6
        let newListArr = listArr.map { [weak self] (item) -> DDAPPConfigureModel_DesktopMe_Item in
            
            switch item.id {
                
            case "2-4-1":
                
                let moneybalance = self?.model?.moneybalance ?? ""
                item.desc = moneybalance
                return item
            case "2-4-2":
                
                let moneybalance = self?.model?.interviewNum ?? ""
                item.desc = moneybalance
                return item
                
            case "2-4-5":
                
                let countIntrest = self?.model?.interestedjobfinderscount ?? ""
                item.desc = countIntrest
                return item
                
                
            case "2-4-6":
                
                let countCommun = (DDCommunicatedStore.sharedStore().communicatedCattles() ?? NSArray()).count
                item.desc = "\(countCommun)"
                return item
                
            default:
                
                return item
                
            }
        }
        
        listArr = newListArr
        self.tableView.reloadData()
        
    }
    
    func headviewContentsClick(){
        
        //点击头像
        headview?.sendClickHeadImg({ [weak self] in
            
            let vc = LDShowPicVC()
            vc.vcDissmiss({ [weak self] in
                self?.setNavTransparent()
                UIApplication.sharedApplication().statusBarHidden = false
                })
            
            let namelogo = self?.model?.logo ?? "default"
            vc.imgUrl = LDCommentAPI.getPicApi(namelogo)
            self?.presentViewController(vc, animated: false, completion: nil)
            
            })
        //点击发布职位
        headview?.sendClickMyResume({ [weak self] in
            
            self?.isAccess({ (ACC) in
                
                if ACC == true{
                
                let vc = DDBossPublishJobViewController.init(type: BossJobType.Default)//
                self?.navigationController?.pushViewController(vc, animated: false)
                
                }else{
                  
                self?.showLDAlertView("请先完善个人信息")
                }
            })
            
//            let vc = DDBossPublishJobViewController.init(type: BossJobType.Default)//DDBossPublishedJobViewController
//            self?.navigationController?.pushViewController(vc, animated: false)
            
            
            
            })
        //点击编辑个人信息
        headview?.sendClickEditMyResume({ [weak self] in
            
            let vc = DDBossEditInfoViewController()
            self?.navigationController?.pushViewController(vc, animated: false)
            })
        
        //点击发布职位状态
        headview?.publishStatusBgView.bk_whenTapped({ [weak self] in
            
            self?.isAccess({ (ACC) in
                
                if ACC == true{
                    
                    let vc = DDBossPublishedJobViewController()
                    self?.navigationController?.pushViewController(vc, animated: false)
                    
                }else{
                    
                    self?.showLDAlertView("请先完善个人信息")
                }
            })
        })
//        //点击活跃度
//        headview?.sendClickActivityLab({ [weak self] in
//            
//            let vc = LDBossActivenessVC()
//            self?.navigationController?.pushViewController(vc, animated: false)
//            })
//        //点击被关注率
//        headview?.sendClickFocusLab({ [weak self] in
//            
//            let vc = LDBossActivenessVC()
//            self?.navigationController?.pushViewController(vc, animated: false)
//            })
    }
    
    //select cell
    func selectIndexOfRow(index:NSIndexPath) {
        
        let className = listArr[index.row].classname
        let title = listArr[index.row].name
        
        let dict = ["class":className,"property":["title":title]]
        
        //待面试 2-4-2 处理
        if listArr[index.row].id == "2-4-2" {
            
            let vc = DDInterviewListVC()
            vc.type = .WaitInterView
            vc.title = title
            navigationController?.pushViewController(vc, animated: true)
            return
        }
        
        //change apptype
        if listArr[index.row].id == "2-4-20" {
            
            let vc = UIApplication.sharedApplication().keyWindow?.rootViewController?.childViewControllers[0]
            DDClientInfoManager.changeClientType(vc, andShowText: "正在切换至求职版首页")
            return
        }
        
        DDMeAdapt.push(dict as [NSObject : AnyObject])
    }
    
    /** nav设置 */
    func setupNav(){
        
        //左边 分享
        let barLeft = UIBarButtonItem(image: UIImage(named:"nav_share_white"), style: UIBarButtonItemStyle.Done, target: self, action: #selector(self.shareBtn))
        navigationItem.leftBarButtonItem = barLeft
        
        //右边 设置
        // 设置
        let barRight = UIBarButtonItem(image: UIImage(named:"nav_setting"), style: UIBarButtonItemStyle.Done, target: self, action: #selector(self.settingBtn))
        navigationItem.rightBarButtonItem = barRight
        
    }
    
    func shareBtn() {
        
        let vc = LDMicroCompanyPage()//DDCompanyMicroPageViewController()
        navigationController?.pushViewController(vc, animated: false)
    }
    
    func settingBtn() {
        
        let vc = mySettingVC()
        navigationController?.pushViewController(vc, animated: false)
    }
    
    
}
extension LDBossMeVC:UITableViewDelegate,UITableViewDataSource {
    
    // MARK: - Table view data source
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        return listArr.count
    }
    
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        
        var cell = tableView.dequeueReusableCellWithIdentifier("cellsmy") as? meListCell
        if cell == nil {
            cell = meListCell.init(style: UITableViewCellStyle.Subtitle, reuseIdentifier: "cellsmy")
        }
        
        cell?.model = getCellModel(indexPath)
        
        return cell!
    }
    
    func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        
        return 50
    }
    
    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        
        selectIndexOfRow(indexPath)
    }
    
    func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        
        
        return 0.1
    }
    
    func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        
        
        return 8
    }
    
    
    
    //MARK: -
    func scrollViewDidScroll(scrollView: UIScrollView) {
        
        //        let offSetY = abs(self.tableView.contentOffset.y) // / 374
        //        let alaph = abs(374 - offSetY)*2 / 374
        //        let image = UIImage.setImageWithColor(LDGolbalColor.Green.colorWithAlphaComponent(alaph))
        //        self.navigationController?.navigationBar.setBackgroundImage(image, forBarMetrics: UIBarMetrics.Default)
        //        self.navigationController?.navigationBar.shadowImage = image
    }
    
    func getCellModel(indexPath:NSIndexPath)->meListCellModel {
        
        let model = meListCellModel()
        model.listName = listArr[indexPath.row].name ?? ""
        model.listPicName = listArr[indexPath.row].img ?? ""
        model.rightDesc = listArr[indexPath.row].desc ?? ""
        
        return model
    }
}
extension LDBossMeVC {
    
    
    
    func isAccess(isTrue: (Bool)->()){
        
        
        isBossInfoCompelete = DDLoginUserManager.objectFromUserDefaultsKey(kBossInfoCompelete) as? Bool ?? false
//        isCompanyInfoCompelete = DDLoginUserManager.objectFromUserDefaultsKey(kCompanyInfoCompelete) as? Bool ?? false
        
//        if isCompanyInfoCompelete == false {
//            
//            LDBossInfoNet.sharedInstance.queryCompanyInfo({ [weak self] (dict) in
//                
//                let model = DDCompanyInfo.yy_modelWithDictionary(dict as [NSObject : AnyObject])
//                
//                self?.isCompanyInfoCompelete = (self?.isCompanyInfo(model))!
//                
//                DDLoginUserManager.saveToUserDefaultsBOOL((self?.isCompanyInfoCompelete)!, forKey: self?
//                    .kCompanyInfoCompelete)
//                
//                
//                }, failure: nil)
//            
//        }
//        
//        if isBossInfoCompelete == false {
        
            DDBossInfoService().queryBossInfoWithRefresh(true) { [weak self] (model) in
                
                self?.isBossInfoCompelete = (LDBossMeVC.isBossInfo(model))
                DDLoginUserManager.saveToUserDefaultsBOOL((self?.isBossInfoCompelete)!, forKey: self?.kBossInfoCompelete)
                isTrue(self?.isBossInfoCompelete ?? false)
                
            }
//        }
    }
    
    class func isBossInfo(model:DDBossInfo?) ->Bool {
        
        
        let isLogo = model?.logo == nil ? false : true
        let isName = model?.name == nil ? false : true
        let isWeixin = model?.weixin == nil ? false : true
        
        var isPosition = true
        if model?.positionname == nil && model?.positioncustomized == nil {
            
            isPosition = false
        }
        
        var isTeamhighlightscount = true
        if model?.teamhighlightscount == nil || model?.teamhighlightscount == "0" {
            
            isTeamhighlightscount = false
        }

        let isTeam = model?.teamintro == nil ? false : true
        
        let isCompany = model?.companyshortname == nil ? false : true
        let isIndus = model?.industry == nil ? false : true
        let isSzie = model?.companysize == nil ? false : true
        
        let isFullName = model?.companyfullname == nil ? false : true
        
        let isWebSize = model?.companywebsite == nil ? false : true

        let isAddress = model?.companyaddress == nil ? false : true
        
        let isAcc = isLogo && isName && isWeixin && isPosition && isTeamhighlightscount && isTeam && isCompany && isIndus && isSzie && isFullName && isWebSize && isAddress
        
        return isAcc
        
    }
    
    func isCompanyInfo(model:DDCompanyInfo?) ->Bool {
        
        let isLogo = model?.ceo_logo == nil ? false : true
        let isName = model?.ceo_name == nil ? false : true
        let isIntro = model?.ceo_intro == nil ? false : true
        
        let isPosition = model?.ceo_position_name == nil ? false : true
        
        let isCompany = model?.company_logo == nil ? false : true
        let isIndus = true//model?.company_size == nil ? false : true
        
        let isProductLogo = model?.product_logo == nil ? false : true
        let isProductName = model?.product_name == nil ? false : true
        let isProductInro = model?.product_strengths  == nil ? false : true
        let isProLight = model?.product_highlights  == nil ? false : true
        
        
        
        let isAcc = isLogo && isName && isIntro && isPosition && isCompany && isIndus  && isProductLogo && isProductName && isProductInro && isProLight
        
        return isAcc
    }
    
}
extension LDBossMeVC:UINavigationBarDelegate{
    
    func navigationBar(navigationBar: UINavigationBar, didPopItem item: UINavigationItem) {
        
        self.navigationController?.navigationBar.barTintColor = UIColor.redColor()
    }
}